package shake

import (
	"data/config"
	"data/view"
	"public/message"
	"public/mysqldb"
	"public/tools"

	"github.com/ant0ine/go-json-rest/rest"
)

//获取用户摇一摇信息
func GetShakeInfo(w rest.ResponseWriter, r *rest.Request) {
	var req GetShakeInfoParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Open_id) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var shake view.Shake_count_tbl
	orm.Where("open_id = ?", req.Open_id).Find(&shake)
	msg := message.GetSuccessMsg()
	msg.Data = shake
	w.WriteJson(msg)
}

//增加摇一摇
func AddCount(w rest.ResponseWriter, r *rest.Request) {
	var req GetShakeInfoParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Open_id) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var shake view.Shake_count_tbl
	orm.Where("open_id = ?", req.Open_id).Find(&shake)

	if shake.Is_shared == 0 { //未分享
		err := orm.Exec("UPDATE shake_count_tbl SET is_shared = 1,count = count + ? where open_id = ?",
			EVERCOUNT, req.Open_id).Error
		if err != nil {
			w.WriteJson(message.GetErrorMsg(message.UnknownError))
			return
		}
	} else {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "至多3次摇一摇"))
		return
	}
	w.WriteJson(message.GetSuccessMsg())
}

//摇一摇
func Action(w rest.ResponseWriter, r *rest.Request) {
	var req GetShakeInfoParam
	tools.GetRequestJsonObj(r, &req)

	//入口参数检测
	if !tools.CheckParam(req.Open_id) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var shake view.Shake_count_tbl
	orm.Where("open_id = ?", req.Open_id).Find(&shake)

	var card view.Card_config_tbl
	if shake.Count > 0 {
		//摇一摇结果
		card = GetRandomCard()
		//次数-1
		err := orm.Exec("UPDATE shake_count_tbl SET count = count-1 where open_id = ?",
			req.Open_id).Error
		if err != nil {
			w.WriteJson(message.GetErrorMsg(message.UnknownError))
			return
		}
	} else {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "次数已用完"))
		return
	}
	msg := message.GetSuccessMsg()
	// mp := make(map[string]interface{})
	// mp["result"] = card
	// mp["count"] = shake.Count - 1
	msg.Data = card
	w.WriteJson(msg)
}
